<template>
  <div class="qrcode-page">
    <div class="page-header">
      <h1 class="title">微信二维码</h1>
      <p class="subtitle">生成和识别微信二维码</p>
    </div>

    <div class="container">
      <div class="qrcode-content">
        <!-- 生成二维码 -->
        <div class="qrcode-generator">
          <div class="generator-card">
            <h2>生成二维码</h2>
            <form @submit.prevent="generateQRCode">
              <div class="form-group">
                <label for="content">二维码内容</label>
                <input
                  id="content"
                  v-model="qrForm.content"
                  type="text"
                  required
                  placeholder="请输入二维码内容"
                />
              </div>
              <div class="form-group">
                <label for="size">二维码大小</label>
                <select id="size" v-model="qrForm.size">
                  <option value="200">200x200</option>
                  <option value="300">300x300</option>
                  <option value="400">400x400</option>
                  <option value="500">500x500</option>
                </select>
              </div>
              <button type="submit" class="btn btn-primary" :disabled="isLoading">
                {{ isLoading ? '生成中...' : '生成二维码' }}
              </button>
            </form>
          </div>
        </div>

        <!-- 二维码显示 -->
        <div v-if="generatedQRCode" class="qrcode-display">
          <div class="qrcode-card">
            <h2>生成的二维码</h2>
            <div class="qrcode-image">
              <img :src="generatedQRCode" alt="生成的二维码" />
            </div>
            <div class="qrcode-info">
              <p><strong>内容:</strong> {{ qrForm.content }}</p>
              <p><strong>大小:</strong> {{ qrForm.size }}x{{ qrForm.size }}</p>
              <p><strong>生成时间:</strong> {{ formatTime(qrCodeInfo.createTime) }}</p>
            </div>
            <div class="qrcode-actions">
              <button @click="downloadQRCode" class="btn btn-secondary">
                下载二维码
              </button>
              <button @click="copyQRCode" class="btn btn-primary">
                复制链接
              </button>
            </div>
          </div>
        </div>

        <!-- 二维码历史 -->
        <div class="qrcode-history">
          <h2>二维码历史</h2>
          <div v-if="qrCodeHistory.length === 0" class="empty-state">
            <p>暂无二维码记录</p>
          </div>
          <div v-else class="history-list">
            <div
              v-for="qr in qrCodeHistory"
              :key="qr.id"
              class="history-item"
            >
              <div class="qr-preview">
                <img :src="qr.qrCodeUrl" :alt="qr.content" />
              </div>
              <div class="qr-info">
                <h3>{{ qr.content }}</h3>
                <p class="qr-meta">
                  <span>大小: {{ qr.size }}x{{ qr.size }}</span>
                  <span>生成时间: {{ formatTime(qr.createTime) }}</span>
                </p>
              </div>
              <div class="qr-actions">
                <button @click="viewQRCode(qr)" class="btn btn-secondary">
                  查看
                </button>
                <button @click="deleteQRCode(qr.id)" class="btn btn-danger">
                  删除
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { wechatApi } from '@/api/wechat'

interface QRCodeInfo {
  id: string
  content: string
  size: number
  qrCodeUrl: string
  createTime: string
}

const qrForm = ref({
  content: '',
  size: 200
})

const isLoading = ref(false)
const generatedQRCode = ref('')
const qrCodeInfo = ref<QRCodeInfo | null>(null)
const qrCodeHistory = ref<QRCodeInfo[]>([])

const generateQRCode = async () => {
  if (!qrForm.value.content) {
    alert('请输入二维码内容')
    return
  }

  isLoading.value = true
  try {
    const response = await wechatApi.generateQRCode(
      qrForm.value.content,
      qrForm.value.size
    )
    
    if (response.code === 200) {
      generatedQRCode.value = response.data.qrCodeUrl
      
      const newQR: QRCodeInfo = {
        id: 'qr_' + Date.now(),
        content: qrForm.value.content,
        size: qrForm.value.size,
        qrCodeUrl: response.data.qrCodeUrl,
        createTime: new Date().toISOString()
      }
      
      qrCodeInfo.value = newQR
      qrCodeHistory.value.unshift(newQR)
      
      alert('二维码生成成功！')
    } else {
      alert('生成二维码失败: ' + response.message)
    }
  } catch (error) {
    console.error('生成二维码失败:', error)
    // 模拟生成成功
    const mockQRUrl = `https://api.qrserver.com/v1/create-qr-code/?size=${qrForm.value.size}x${qrForm.value.size}&data=${encodeURIComponent(qrForm.value.content)}`
    
    generatedQRCode.value = mockQRUrl
    
    const newQR: QRCodeInfo = {
      id: 'qr_' + Date.now(),
      content: qrForm.value.content,
      size: qrForm.value.size,
      qrCodeUrl: mockQRUrl,
      createTime: new Date().toISOString()
    }
    
    qrCodeInfo.value = newQR
    qrCodeHistory.value.unshift(newQR)
    
    alert('模拟二维码生成成功！')
  } finally {
    isLoading.value = false
  }
}

const downloadQRCode = () => {
  if (!generatedQRCode.value) return
  
  const link = document.createElement('a')
  link.href = generatedQRCode.value
  link.download = `qrcode_${Date.now()}.png`
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

const copyQRCode = async () => {
  if (!generatedQRCode.value) return
  
  try {
    await navigator.clipboard.writeText(generatedQRCode.value)
    alert('二维码链接已复制到剪贴板')
  } catch (error) {
    console.error('复制失败:', error)
    alert('复制失败，请手动复制')
  }
}

const viewQRCode = (qr: QRCodeInfo) => {
  generatedQRCode.value = qr.qrCodeUrl
  qrCodeInfo.value = qr
}

const deleteQRCode = (id: string) => {
  if (confirm('确定要删除这个二维码吗？')) {
    qrCodeHistory.value = qrCodeHistory.value.filter(qr => qr.id !== id)
    
    if (qrCodeInfo.value?.id === id) {
      generatedQRCode.value = ''
      qrCodeInfo.value = null
    }
  }
}

const formatTime = (timeString: string) => {
  return new Date(timeString).toLocaleString('zh-CN')
}

onMounted(() => {
  // 模拟加载二维码历史
  const mockQRs: QRCodeInfo[] = [
    {
      id: 'qr_001',
      content: 'https://example.com',
      size: 200,
      qrCodeUrl: 'https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=https://example.com',
      createTime: new Date(Date.now() - 3600000).toISOString()
    },
    {
      id: 'qr_002',
      content: '微信场景实现系统',
      size: 300,
      qrCodeUrl: 'https://api.qrserver.com/v1/create-qr-code/?size=300x300&data=微信场景实现系统',
      createTime: new Date(Date.now() - 7200000).toISOString()
    }
  ]
  
  qrCodeHistory.value = mockQRs
})
</script>

<style scoped>
.qrcode-page {
  min-height: 100vh;
  position: relative;
}

.page-header {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 0 0 30px 30px;
  margin-bottom: 40px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.title {
  font-size: 2.5rem;
  font-weight: 700;
  background: linear-gradient(135deg, #667eea, #764ba2);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  margin-bottom: 16px;
}

.subtitle {
  font-size: 1.2rem;
  color: #666;
  max-width: 600px;
  margin: 0 auto;
}

.qrcode-content {
  max-width: 1200px;
  margin: 0 auto;
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 40px;
}

.qrcode-generator,
.qrcode-display,
.qrcode-history {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 20px;
  padding: 30px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.qrcode-generator h2,
.qrcode-display h2,
.qrcode-history h2 {
  font-size: 1.5rem;
  font-weight: 600;
  color: #333;
  margin-bottom: 24px;
  text-align: center;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  font-weight: 500;
  color: #333;
  margin-bottom: 8px;
}

.form-group input,
.form-group select {
  width: 100%;
  padding: 12px 16px;
  border: 2px solid #e5e5e5;
  border-radius: 8px;
  font-size: 16px;
  transition: border-color 0.3s ease;
}

.form-group input:focus,
.form-group select:focus {
  outline: none;
  border-color: #667eea;
}

.btn {
  width: 100%;
  padding: 14px;
  font-size: 16px;
  font-weight: 600;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.qrcode-image {
  text-align: center;
  margin-bottom: 20px;
}

.qrcode-image img {
  max-width: 100%;
  height: auto;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.qrcode-info {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 20px;
}

.qrcode-info p {
  margin-bottom: 8px;
  color: #333;
}

.qrcode-info p:last-child {
  margin-bottom: 0;
}

.qrcode-actions {
  display: flex;
  gap: 12px;
}

.qrcode-actions .btn {
  flex: 1;
}

.empty-state {
  text-align: center;
  padding: 40px 20px;
  color: #666;
}

.history-list {
  max-height: 400px;
  overflow-y: auto;
}

.history-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 16px;
  border: 1px solid #e5e5e5;
  border-radius: 8px;
  margin-bottom: 12px;
  background: #f9f9f9;
}

.qr-preview {
  width: 60px;
  height: 60px;
  flex-shrink: 0;
}

.qr-preview img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 4px;
}

.qr-info {
  flex: 1;
  min-width: 0;
}

.qr-info h3 {
  font-size: 1rem;
  font-weight: 600;
  color: #333;
  margin-bottom: 4px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.qr-meta {
  font-size: 0.8rem;
  color: #666;
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.qr-actions {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.qr-actions .btn {
  padding: 6px 12px;
  font-size: 0.8rem;
  min-width: 60px;
}

.btn-danger {
  background: #fa5151;
  color: white;
}

.btn-danger:hover {
  background: #e74c3c;
}

@media (max-width: 768px) {
  .qrcode-content {
    grid-template-columns: 1fr;
    gap: 20px;
  }
  
  .title {
    font-size: 2rem;
  }
  
  .subtitle {
    font-size: 1rem;
  }
  
  .qrcode-actions {
    flex-direction: column;
  }
  
  .history-item {
    flex-direction: column;
    text-align: center;
  }
  
  .qr-actions {
    flex-direction: row;
    justify-content: center;
  }
}
</style>
